package com.klikmee.sms.core.base.postman;

import java.text.MessageFormat;

import org.apache.log4j.Logger;

import com.klikmee.sms.cef.services.ws.ServiceResponseReport;
import com.klikmee.sms.core.base.EventManager;
import com.klikmee.sms.core.base.util.States;
import com.klikmee.sms.core.commons.events.AppEvent;
import com.klikmee.sms.core.commons.queues.QueueItem;
import com.klikmee.sms.core.model.BulkMessage;

public class BulkDeliveryReportQueueItemProcessorImpl extends ItemProcessorBase<BulkMessage> {

	/**
	 * Logger instance
	 */
	Logger	logger	= Logger.getLogger( BulkDeliveryReportQueueItemProcessorImpl.class );

	@Override
	public boolean process(QueueItem<BulkMessage> item) {
		// extract payload, override endpoint address and deliver status report
		BulkMessage bulkMessage = item.getPayload();
		String endpoint = bulkMessage.getChargingCategory().getService().getEndpoint();

		// build ResponseReport obj
		ServiceResponseReport responseReport = createServiceResponseReport( bulkMessage );

		overrideEndpointAddress( endpoint );
		// try to deliver report
		try {
			serviceProxy.onResponseReport( responseReport );
			logger.info( MessageFormat.format( "Delivered status report to service name = [{0}], message id = [{1}]", bulkMessage.getChargingCategory().getService().getName(), bulkMessage.getId() ) );

			// announce delivery report handed over to service event
			AppEvent appEvent = new AppEvent( EventManager.BULK_DELIVERY_REPORT_DELIVERED_TO_SERVICE, bulkMessage );
			this.dispatcher.dispatch( appEvent );

			return true;
		}
		catch (Exception e) {
			logger.fatal( String.format( "Failed to deliver status report to service, BulkMessage[%s]", bulkMessage.getId() ), e );
			return false;
		}
	}

	private ServiceResponseReport createServiceResponseReport(BulkMessage outgoingMessage) {
		ServiceResponseReport report = new ServiceResponseReport();
		report.setResponseId( outgoingMessage.getId() );
		report.setStatus( outgoingMessage.getState().equals( States.OutgoingMessage.DELIVERED ) ? "DELIVERED" : "NOT DELIVERED" );

		return report;
	}

}
